package com.example.templateapp.widget

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.templateapp.R
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder
import com.xuexiang.xutil.display.ScreenUtils

object BottomSheetListDialog {

    fun getDialog(
        context: Context,
        title: String,
        adapter: RecyclerView.Adapter<RecyclerViewHolder>,
        isFullScreen: Boolean = false
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(context)
        val view =
            LayoutInflater.from(context).inflate(R.layout.dialog_bottom_sheet, null)


        val rv = view.findViewById<RecyclerView>(R.id.recyclerView)
        initDialogList(rv, context)


        rv.adapter = adapter

        val titleTv = view.findViewById<TextView>(R.id.title)
        val cancelBtn = view.findViewById<TextView>(R.id.cancel)
        val confirmBtn = view.findViewById<TextView>(R.id.confirm)
        titleTv.text = title
        cancelBtn.visibility = View.VISIBLE
        confirmBtn.visibility = View.INVISIBLE

        cancelBtn.setOnClickListener { dialog.dismiss() }

        if (isFullScreen) {
            dialog.behavior.peekHeight = ScreenUtils.getScreenHeight()
        }
        dialog.setContentView(view)

        dialog.delegate.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            .also {
                it?.setBackgroundColor(Color.TRANSPARENT)
            }
        dialog.window?.setWindowAnimations(R.style.bottom_dialog_anim)
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        return dialog
    }

    private fun initDialogList(
        recyclerView: RecyclerView,
        context: Context
    ) {
        val manager = GridLayoutManager(context, 4)
        recyclerView.layoutManager = manager
        recyclerView.setItemViewCacheSize(24)
    }

}